package com.web.listeners;

import org.testng.IClass;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

import com.app.AppContext;
import com.web.imp.AbstractWebTest;
import com.web.lang.LanguageConfig;
import com.web.listeners.imp.ScreenshotConfig;
import com.web.model.ScreenShot;
import com.web.model.WebBrowser;

public class ScreenShotListener extends TestListenerAdapter {
	
	private static ScreenshotConfig config = AppContext.getBean(ScreenshotConfig.class);
	
	@Override
	public void onTestFailure(ITestResult testResult) {
		
		AbstractWebTest testInstance = (AbstractWebTest) testResult.getInstance();
		
		if(testInstance.isThereBrowser()){
		
			WebBrowser browser = testInstance.getBrowser();
				
			ScreenShot screenShot = browser.takeScreenShot();
			saveTestScreenShot(screenShot, testResult);
		}
	}

	private void saveTestScreenShot(ScreenShot screenShot, ITestResult testResult) {
		
		IClass testClass = testResult.getTestClass();
		Class<?> realTestClass = testClass.getRealClass();
		ITestNGMethod method = testResult.getMethod();
		
		String name = LanguageConfig.getLanguage() + " - " + realTestClass.getName() + "." + method.getMethodName() + "()";
		screenShot.saveWithDate(config.getScreenShotsFilePath(), name);
	}
	@Override
	public void onTestSuccess(ITestResult testResult) {

	}
}
